package servlets.ads;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;
import structures.ProductList;

public class SearchProducts extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String EBAY_URL_BASE = "http://ebayrestservice.herokuapp.com/";
	private static final String AMAZON_URL_BASE = "http://amazonrestservice.herokuapp.com/";
	private static final String ISELL_URL_BASE = "http://localhost:8080/DatabaseRESTWebService/";

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		String keywords = request.getParameter("keywords").replace(" ", "%20");
		ProductList ebayList = new ProductList();
		ProductList amazonList = new ProductList();
		ProductList isellList = new ProductList();
		JsonManager jsonManager = new JsonManager();
		//String answer = "[";
		String answer = "";

		System.out.println("ISELLTOYOU: "+keywords);
		
		try {
			// Leggo i prodotti
			answer += readProducts(EBAY_URL_BASE + "ebayProducts?keywords=", keywords);	
			ebayList = jsonManager.toProductList(answer);
			
			answer = readProducts(AMAZON_URL_BASE + "amazonProducts?keywords=", keywords);
			amazonList = jsonManager.toProductList(answer);
			
			answer = readProducts(ISELL_URL_BASE + "SearchProducts?keywords=", keywords);
			isellList = jsonManager.toProductList(answer);
			
			ebayList.getList().addAll(amazonList.getList());
			ebayList.getList().addAll(isellList.getList());
			
			String result = jsonManager.generateJSON(ebayList);
			
			try {
				response.getWriter().write(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (Exception e1) {
			
		}
	}

	private String readProducts(String fromUrl, String keywords) throws IOException,
			MalformedURLException, ProtocolException {
		String inputLine;
		String answer;
		BufferedReader reader;
		StringBuffer responseBuffer;
		String url = fromUrl + keywords;
		String cleanUrl = url.replace(" ", "%20");
		
		HttpURLConnection httpConnection = (HttpURLConnection) new URL(cleanUrl).openConnection();
		httpConnection.setRequestMethod("GET");
		httpConnection.setDoOutput(true); 
		httpConnection.setDoInput(true);
		httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		
		reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
		
		responseBuffer = new StringBuffer();
		
		while ((inputLine = reader.readLine()) != null) {
			responseBuffer.append(inputLine);
		}
		reader.close();

		answer = responseBuffer.toString();
		return answer;
	}

}
